import type { Ref } from 'vue'
import { ref, nextTick } from 'vue'
import { useI18n } from '@/locales/useI18n'
import { message } from 'ant-design-vue'
import { cloneDeep } from 'lodash-es'
import {
  useDrawer as useBasicDrawer,
  RegisterFn,
  DrawerProps
} from '@/components/Drawer'

const { t } = useI18n()

interface ReturnMethods {
  onClose: () => void
  onShow: (row?: any) => void
  getInnerForm: (validateForm: PromiseFn) => Promise<any>
}

export type UseDrawerReturnType<T> = [
  RegisterFn,
  ReturnMethods,
  Ref<T | undefined>
]

export function useDrawer<T = any>(
  bind: Partial<DrawerProps> = {}
): UseDrawerReturnType<T> {
  const [register, { openDrawer, closeDrawer: onClose, setDrawerProps }] =
    useBasicDrawer()

  const currentItem = ref<T>()
  const onShow = function (row?: T) {
    if (row) {
      currentItem.value = cloneDeep(row)
    }
    openDrawer()
  }

  const bindValue = Object.assign(
    { width: '40%', bodyStyle: { padding: 0 } },
    bind
  )

  nextTick(() => {
    setDrawerProps(bindValue)
  })

  const getInnerForm = function (validateFormFn: PromiseFn) {
    return validateFormFn().catch((err: any) => {
      message.warning(t('system.form.warning'))
      return Promise.reject(err)
    })
  }

  return [
    register,
    {
      onShow,
      onClose,
      getInnerForm
    },
    currentItem
  ]
}

export default useDrawer